<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="format-detection" content="telephone=no,email=no" />
		<title>商品详情页</title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" />
	</head>

	<body>
		<header class="mui-bar mui-bar-nav transparent-bg">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">商品详情</h1>
			
		</header>
		<div id="scrollDiv" class="scroll-div">
			<div class="mui-content transparent">
				<div id="slider" class="mui-slider">
					<div class="mui-slider-group mui-slider-loop" id="sliderImg" style="margin: -5px 0;">
					</div>
					<div class="mui-slider-indicator">
					</div>
					<div class="mui-pull-loading mui-spinner custom-loading"></div>
				</div>
			</div>
		</div>
		<footer id="s-actionBar-container" class="transparent">
	        <div id="s-actionbar" class="action-bar mui-flex">
	            <div class="tocart cell iconfont icon-gouwuche" id="goCart">购物车<span class="plus-one">1</span></div>
	            <div class="addfav cell iconfont icon-xingxing" id="favProduct">收藏</div>
	            <div class="toshop cell iconfont icon-dianpu" id="goshop">店铺</div>
	            <button class="cart cell" id="addToCart">加入购物车</button>
	            <button class="buy cell" id="easyBuyBtn">立即购买</button>
	            <button class="nobuy cell" id="noBuy" style="display: none;">已 下 架</button>
	        </div>
	    </footer>
		
	
		<script src="js/jquery-1.8.0.min.js"></script>
		<script src="js/mui.min.js"></script>
		<script src="js/app.js"></script>
		<script src="js/mui.zoom.js"></script>
		<script src="js/mui.previewimage.js"></script>
		<script>
			mui.init();
			
			var shares = {},
				productId,
				skuId =[0,0,0],
				skuLen,
				productInfo='',
				productImg,
				stock=0;
			var slider=document.getElementById('sliderImg'),
				loadArr=document.getElementsByClassName('custom-loading');
			slider.style.height=slider.offsetWidth+'px';
			setTimeout(function(){
				loadArr[0].parentNode.removeChild(loadArr[0]);
			},5000);
			mui.plusReady(function() {
				var w=plus.nativeUI.showWaiting('',{padlock:true});
				plus.webview.currentWebview().setStyle({scrollIndicator:'none'});
				productId = plus.webview.currentWebview().productId;
				mui.ajax(URL+'api/product/GetProductDetail/'+productId,{
					dataType:'json',
					type:'get',
					timeout:10000,
					success:function(data){
//			            console.log(data)
						if(data.Success=='true'){
							var imgLen=data.Product.ImagePath.length;
							if(imgLen>0){
			                    //轮播图
			                    productImg=data.Product.ImagePath[0].replace('.png','_150.png');
								var outputimg = "",
									outputright = "";
					            outputimg+='<div class="mui-slider-item mui-slider-item-duplicate"><div class="mui-zoom"><img src="'+data.Product.ImagePath[imgLen-1].replace('.png','_350.png')+'" /></div></div>';
					            for (var i = 0; i < imgLen; i++) {
					            	outputimg+='<div class="mui-slider-item"><div class="mui-zoom"><img src="'+data.Product.ImagePath[i].replace('.png','_350.png')+'" data-preview-src="" data-preview-group="1" /></div></div>';
					                var right = '<div class="mui-indicator';
					                if (i == 0) {
					                    right = right + ' mui-active';
					                }
					                right = right + '"></div>';
					                outputright += right;
					            }
					            outputimg+='<div class="mui-slider-item mui-slider-item-duplicate"><div class="mui-zoom"><img src="'+data.Product.ImagePath[0].replace('.png','_350.png')+'"  /></div></div>';
					            slider.innerHTML=outputimg;
					            document.getElementsByClassName('mui-slider-indicator')[0].innerHTML=outputright;
								mui('#slider').slider({interval:5000});
					            mui.previewImage();
							}else{
								document.getElementById('slider').style.display='none';
							}
							
							productInfo+='<ul class="mui-table-view" style="margin-top:1px">'+
								'<li class="mui-table-view-text">'+
									'<div class="goods-info">'+
										'<div class="goods-share" id="goodsShare"><i class="iconfont icon-fenxiang"></i><br />分享</div>'+
										'<h3 id="pName">'+data.Product.ProductName+'</h3>';
										if(data.Product.ShortDescription!='')
											productInfo+='<h4 id="pShortName">'+data.Product.ShortDescription+'</h4>';
										productInfo+='<h5 class="p-mark-price"><s>市场价：¥'+data.Product.MarketPrice+'</s></h5>'+
										'<p class="p-price"><a class="mui-pull-right">评价数：(<em>'+data.Product.CommentCount+'</em>条)</a>商城价：<span id="pPrice">¥ '+data.Product.MinSalePrice+'</span></p>'+
									'</div>'+
								'</li>';
								if(data.Shop.FreeFreight!=0 || data.Shop.CouponCount!=0){
									productInfo+='<li class="mui-table-view-text">'+
										'<div class="goods-onsale">'+
											'<label>促销</label>'+
											'<div class="goods-onsale-detail">';
												if(data.Shop.CouponCount!=0)
													productInfo+='<p class="goods-coupon"><a id="goShopCoupon" class="mui-navigate-right" data-id="'+data.Shop.Id+'"><i>优惠券</i>'+data.Shop.CouponCount+' 张可领优惠券</a></p>';
												if(data.Shop.FreeFreight!=0)
													productInfo+='<p><i>满免</i>满额'+data.Shop.FreeFreight+'免运费</p>';
											productInfo+='</div>'+
										'</div>'+
									'</li>';
								}
								productInfo+='<li class="mui-table-view-text">'+
									'<div class="goods-sku" id="choose">'+
										'<div class="goods-num">'+
											'<label>数量</label>'+
											'<div id="pMaxCount" class="mui-numbox" data-numbox-min="1">'+
												'<button class="mui-btn mui-numbox-btn-minus" type="button">-</button>'+
												'<input id="porductCount" class="mui-numbox-input" type="number" value="1" />'+
												'<button class="mui-btn mui-numbox-btn-plus" type="button">+</button>'+
											'</div>';
											if(data.IsOnLimitBuy=='true'){
												productInfo+='<i style="margin-left:15px; color:#e3393c; font-size:14px">同ID限购'+data.MaxSaleCount+'件</i>';
											}
										productInfo+='</div>'+
									'</div>'+
								'</li>'+
								'<li class="mui-table-view-text">'+
									'<div class="goods-shop">'+
										'<h4>'+data.Shop.Name+'</h4>'+
										'<h5>宝贝数量：<span>'+data.Shop.ProductNum+'</span></h5>'+
										'<p>'+
											'<span>商品：<em>'+data.Shop.ProductAndDescription+'</em></span>'+
											'<span>发货：<em>'+data.Shop.SellerServiceAttitude+'</em></span>'+
											'<span>服务：<em>'+data.Shop.SellerDeliverySpeed+'</em></span>'+
										'</p>'+
									'</div>'+
								'</li>'+
							'</ul>'+
							'<ul class="mui-table-view mt10">'+
								'<li class="mui-table-view-cell" id="showProDetail">'+
									'<a class="mui-navigate-right">图文详情</a>'+
								'</li>'+
							'</ul>'+
							'<ul class="mui-table-view mt10">'+
								'<li class="mui-table-view-text">'+
									'<div class="goods-comment">'+
										'<span class="mui-pull-right gray">共<em>'+data.Product.CommentCount+'</em>条 评论</span>'+
										'评论<span class="comment-nice">好评<em>'+data.Product.NicePercent+'%</em></span>'+
									'</div>'+
								'</li>'+
							'</ul>'+
							'<div class="p-detail mt10">'+
								'<h4>商品图文详情</h4>'+
								'<div class="p-detail-html" id="ProductDescription">'+
								'</div>'+
							'</div>';
							document.getElementsByClassName('mui-content')[0].insertAdjacentHTML('beforeend',productInfo);
							mui('.mui-numbox').numbox();
							if(data.Shop.VShopId!=-1)
								$('#goshop').data('vshopid',data.Shop.VShopId);
							else
								$('#goshop').addClass('gray');
							
							if(data.Product.IsFavorite)
								$('#favProduct').addClass('red');
							
							if(data.Product.ProductSaleStatus==2){
								document.getElementById('easyBuyBtn').style.display='none';
								document.getElementById('addToCart').style.display='none';
								document.getElementById('noBuy').style.display='block';
							}
							
							var chooseSku='',skuStr;
							if(data.Color.length>0){
								skuStr='';
								for(var i=data.Color.length-1;i>=0;i--){
									skuStr+='<span st="0" cid="'+data.Color[i].SKUId+'" class="enabled">'+data.Color[i].Value+'</span>'
								}
								chooseSku+='<div class="choose-sku"><label>颜色</label><div>'+skuStr+'</div></div>'
							}
							if(data.Size.length>0){
								skuStr='';
								for(var i=data.Size.length-1;i>=0;i--){
									skuStr+='<span st="1" cid="'+data.Size[i].SKUId+'" class="enabled">'+data.Size[i].Value+'</span>'
								}
								chooseSku+='<div class="choose-sku"><label>尺寸</label><div>'+skuStr+'</div></div>'
							}
							if(data.Version.length>0){
								skuStr='';
								for(var i=data.Version.length-1;i>=0;i--){
									skuStr+='<span st="2" cid="'+data.Version[i].SKUId+'" class="enabled">'+data.Version[i].Value+'</span>'
								}
								chooseSku+='<div class="choose-sku"><label>规格</label><div>'+skuStr+'</div></div>'
							}
							$('#choose').prepend(chooseSku);
							//if(data.Color.length>0 || data.Size.length>0 || data.Version.length>0)
								getSKUInfo();
							
							var productDesc=document.getElementById('ProductDescription');
							
							var scrollDiv=$('#scrollDiv');
							document.getElementById('showProDetail').addEventListener('tap',function(){
								if(productDesc.innerHTML==''){
									productDesc.innerHTML=data.Product.ProductDescription;
								}
								scrollDiv.scrollTop($('.p-detail').offset().top+scrollDiv.scrollTop()-50)
							});
							/*var scrollHeight = $('#ProductDescription').offset().top;
							var windowHeight = $(this).height();
							scrollDiv.scroll(function(){
								var scrollTop = $(this).scrollTop();
								console.log(scrollTop + windowHeight)
									console.log(scrollHeight)
								if (scrollTop + windowHeight >= scrollHeight-100) {
								    if(productDesc.innerHTML==''){
										productDesc.innerHTML=data.Product.ProductDescription;
								    }
								}
							});*/
							
							app.stopHref(mui('#ProductDescription'));
							
							if(data.IsOnLimitBuy=='true'){
								document.getElementsByClassName('mui-title')[0].innerText=data.Title;
								document.getElementById('goCart').style.display='none';
								document.getElementById('easyBuyBtn').innerText='立即抢购';
								
								var intDiff=data.Second;
								setInterval(function () {
						            var hour = 0,
						                minute = 0,
						                second = 0;
						            if (intDiff > 0) {
						                hour = Math.floor(intDiff / (60 * 60));
						                minute = Math.floor(intDiff / 60) - (hour * 60);
						                second = Math.floor(intDiff) - (hour * 60 * 60) - (minute * 60);
						            }
						            if (minute <= 9) minute = '0' + minute;
						            if (second <= 9) second = '0' + second;
						            document.getElementById('addToCart').innerHTML='<span class="iconfont icon-time"></span> '+hour + ':' + minute + ':' + second;
						            intDiff--;
						        }, 1000);
								
							}else{
								bindAddCart();
							}
							
							w.close();
							document.getElementsByClassName("mui-content")[0].className="mui-content"
							document.getElementById('s-actionBar-container').className='';
						}
					},
					error:function(xhr,type,errorThrown){
						w.close();
						reloadWvLoad();
					}
				});
			
				
				plus.share.getServices(function(s) {
					if (s && s.length > 0) {
						for (var i = 0; i < s.length; i++) {
							var t = s[i];
							shares[t.id] = t;
						}
					}
				}, function() {
					plus.nativeUI.toast('获取分享列表失败')
				});
				
			});
			
			function getSKUInfo(){
				var SKUDATA = null,
					skuLen=$('#choose .choose-sku').length,
					skuIndex;
				mui.ajax(URL+'api/product/GetSKUInfo',{
					data:{productId:productId},
					dataType:'json',
					type:'get',
					timeout:20000,
					success:function(data){

				        SKUDATA=data.SkuArray;
				        if(skuLen==1){
				        	$('#choose .enabled').each(function(){
						        skuIndex = parseInt($(this).attr('st'));
						        skuId[skuIndex] = $(this).attr('cid');
						        
						        if(filterArr(SKUDATA,skuId.join(';'))==''){
					        		$(this).removeClass().addClass('disabled');
					        	}
				        	});
				        }
				        if(skuLen==2){
				        	$('#choose').on('tap','.enabled',function () {
				        		skuIndex = parseInt($(this).attr('st'));
						    	skuId[skuIndex] = $(this).attr('cid');
				        		$(this).parents('.choose-sku').siblings('.choose-sku').find('span').each(function(){
				        			skuIndex = parseInt($(this).attr('st'));
						        	skuId[skuIndex] = $(this).attr('cid');
						        	if(filterArr(SKUDATA,skuId.join(';'))==''){
						        		$(this).removeClass().addClass('disabled');
						        	}else{
						        		$(this).removeClass('disabled').addClass('enabled');
						        	}
				        		});
				        	});
				        }
				        if(skuLen==3){
				        	$('#choose').on('tap','.enabled',function () {
				        		skuIndex = parseInt($(this).attr('st'));
						    	skuId[skuIndex] = $(this).attr('cid');
						    	var sibSku=$(this).parents('.choose-sku').siblings('.choose-sku'),
						    		sibOne=sibSku.eq(0).find('.selected'),
						    		sibTwo=sibSku.eq(1).find('.selected');
						    	
						    	//选中兄弟sku其中一个测试另外一个是否可选
						    	skuIndex = parseInt(sibOne.attr('st'));
						        skuId[skuIndex] = sibOne.attr('cid');
					    		sibSku.eq(1).find('span').each(function(){
				        			skuIndex = parseInt($(this).attr('st'));
						        	skuId[skuIndex] = $(this).attr('cid');
						        	if(filterArr(SKUDATA,skuId.join(';'))==''){
						        		$(this).removeClass().addClass('disabled');
						        	}else{
						        		$(this).removeClass('disabled').addClass('enabled');
						        	}
				        		});
				        		
						    	skuIndex = parseInt(sibTwo.attr('st'));
						        skuId[skuIndex] = sibTwo.attr('cid');
					    		sibSku.eq(0).find('span').each(function(){
				        			skuIndex = parseInt($(this).attr('st'));
						        	skuId[skuIndex] = $(this).attr('cid');
						        	if(filterArr(SKUDATA,skuId.join(';'))==''){
						        		$(this).removeClass().addClass('disabled');
						        	}else{
						        		$(this).removeClass('disabled').addClass('enabled');
						        	}
				        		});
				        		
						    	
				        		
				        	});
				        }
				        $('#choose').on('tap','.enabled',function () {
				            var _that = $(this);
				            _that.addClass('selected').siblings().removeClass('selected');
				            var len = $('#choose .selected').length;
				            if(len===skuLen){
							    for (var i = 0; i < len; i++) {
							        skuIndex = parseInt($('#choose .selected').eq(i).attr('st'));
							        skuId[skuIndex] = $('#choose .selected').eq(i).attr('cid');
							    }
							    var select=filterArr(SKUDATA,skuId.join(';'))
							    $('#pPrice').text('¥ '+select[0].Price);
							    stock=select[0].Stock;
						    }
				        });
				        if (skuLen != 0){
						    $(".choose-sku").each(function () {
						        $(this).find('.enabled').first().trigger("tap");
						    });
						}else if(skuLen==0){
							stock=SKUDATA[0].Stock;
						}
				        
					},
					error:function(xhr,type,errorThrown){
						//plus.nativeUI.toast('sku请求超时')
					}
				});
			}
			function filterArr(data, context) {
			    var arr = [];
				for (var i = 0; i < data.length; i++) {
					if(data[i].SKUId==context){
						arr.push(data[i]);
					}
				}
			    return arr;
			}

			//分享链接点击事件
			mui('.mui-content').on('tap', '#goodsShare', function() {
				var ids = [{
						id: "weixin",
						ex: "WXSceneSession"
					}, {
						id: "weixin",
						ex: "WXSceneTimeline"
					}, {
						id: "qq"
					}],
					bts = [{
						title: "发送给微信好友"
					}, {
						title: "分享到微信朋友圈"
					}
//					, {
//						title: "分享给QQ好友"
//					}
					];
				plus.nativeUI.actionSheet({
					cancel: "取消",
					buttons: bts
				}, function(e) {
					var i = e.index;
					if (i > 0) {
						var s_id = ids[i - 1].id;
						var share = shares[s_id];
						if (share.authenticated) {
							shareMessage(share, ids[i - 1].ex);
						} else {
							share.authorize(function() {
								shareMessage(share, ids[i - 1].ex);
							}, function(e) {
								plus.nativeUI.toast("认证授权失败：" + e.code);
							});
						}
					}
				});
			});
			
			function shareMessage(share, ex) {
				var ProductHref=URL+'product/detail/'+productId;
				var msg = {
					extra: {
						scene: ex
					}
				};
				msg.href = ProductHref;
				msg.title = document.getElementById('pName').innerText;
				msg.content =document.getElementById('pShortName')? document.getElementById('pShortName').innerText:'';
				/*if (~share.id.indexOf('weibo')>=0) {
					msg.content += '，<a href="'+ProductHref+'">Go血拼！ ></a>';
				}*/
				//msg.thumbs=productImg;
				//msg.pictures=productImg;
				msg.pictures = ["_www/images/logo.png"];
				msg.thumbs = ["_www/images/logo.png"];
				share.send(msg, function() {
					plus.nativeUI.toast("分享到\"" + share.description + "\"成功！ ");
				}, function(e) {
					plus.nativeUI.toast("分享到\"" + share.description + "\"取消");
				});
			}
			
			function getskuid() {
			    var sku = '';
			    sku = productId +'_'+ skuId.join('_') ;
			    return sku;
			}
			
			mui('.mui-content').on('tap', '#goShopCoupon', function() {
				var id = this.getAttribute('data-id');
				mui.openWindow({
					id:'vshop-coupon.html',
					url:'vshop/vshop-coupon.html',
					extras:{
						shopid:id
				    },
					show: {
						autoShow:true,
						aniShow: 'pop-in'
					},
					waiting: {
						autoShow: false
					}
				});
			});
			
			function bindAddCart(){
				document.getElementById("addToCart").addEventListener('tap',function () {
					if(app.isLogin()){
						setTimeout(function(){
							var len = $('#choose .choose-sku .selected').length;
							if (len === $('#choose .choose-sku').length) {
								var sku=getskuid(),
									count=document.getElementById('porductCount').value,
									data={skuId:sku,count:count};
								if(count<=stock){
									var w=plus.nativeUI.showWaiting('',{padlock:true});
									mui.ajax(URL+'api/Cart/PostAddProductToCart',{
										data:JSON.stringify(data),
										dataType:'json',
										contentType:'application/json',
										type:'post',
										timeout:10000,
										success:function(data){
											w.close();
											if(data.Success=="true"){
												plus.nativeUI.toast('加入购物车成功');
												$('.plus-one').text(count).css({ 'top': 0, 'opacity': 0, 'display': 'block' }).animate({ 'top': '-15px', 'opacity': '1' }, 500).fadeOut();
											}else{
												plus.nativeUI.toast('加入购物车失败');
											}
										},
										error:function(xhr,type,errorThrown){
											w.close();
											plus.nativeUI.toast('加入购物车失败，请检查网络')
										}
									});
								}else{
									plus.nativeUI.toast('库存不足，当前规格库存为'+stock);
								}
							}
							else{
								plus.nativeUI.toast('请选择商品规格');
							}
						},100);
					}else{
						showLogin();
					}
				});
			}
			
			document.getElementById("favProduct").addEventListener('tap',function () {
				if(app.isLogin()){
					var w=plus.nativeUI.showWaiting('',{padlock:true});
					mui.ajax(URL+'api/product/PostAddFavoriteProduct',{
						data:JSON.stringify({productId:productId}),
						dataType:'json',
						contentType:'application/json',
						type:'POST',
						timeout:10000,
						success:function(data){
							w.close();
							if(data.Success=="true"){
								plus.nativeUI.toast(data.Msg);
								$('#favProduct').toggleClass('red');
							}else{
								plus.nativeUI.toast('收藏商品失败');
							}
						},
						error:function(xhr,type,errorThrown){
							w.close();
							plus.nativeUI.toast('收藏失败，请检查网络')
						}
					});
				}else{
					showLogin();
				}
				
			});
			
			document.getElementById('goCart').addEventListener('tap',function(){
				if(app.isLogin()){
					mui.openWindow({
						id:'cart-box.html',
						url:'cart-box.html',
						show: {
							autoShow:true,
							aniShow: 'pop-in'
						},
						waiting: {
							autoShow: false
						}
					});
				}else{
					showLogin();
				}
			});
			
			document.getElementById("easyBuyBtn").addEventListener('tap',function () {
				if(app.isLogin()){
					setTimeout(function(){
						var len = $('#choose .choose-sku .selected').length;
						if (len === $('#choose .choose-sku').length) {
							var sku=getskuid(),
								count=document.getElementById('porductCount').value;
							if(count<=stock){
								mui.openWindow({
									id:'order-submit.html',
									url:'order-submit.html',
									extras:{
										skuIdCount:JSON.stringify({skuId:sku,count:count})
								    },
									show: {
										autoShow:true,
										aniShow: 'pop-in'
									},
									waiting: {
										autoShow: false
									}
								});
							}else{
								plus.nativeUI.toast('库存不足，当前规格库存为'+stock);
							}
						}
						else{
							plus.nativeUI.toast('请选择商品规格');
						}
					},100)
				}else{
					showLogin();
				}
			});
			
			document.getElementById('goshop').addEventListener('tap',function(){
				if($(this).hasClass('gray')){
					plus.nativeUI.toast('该店铺暂未开通微店')
				}else{
					var vshopid = $(this).data('vshopid');
					showVshop(vshopid,'/');
				}
			});
			
		</script>
	</body>

</html>